from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User
from .serializers import UserSerializer, UserInfoDto
from django.contrib.auth.hashers import make_password, check_password

class LoginView(APIView):
    def post(self, request):
        phone = request.query_params.get('phone')
        password = request.query_params.get('password')

        try:
            user = User.objects.get(phone=phone)
            if check_password(password, user.password):
                return Response({"code": 0, "msg": "", "data": {"user_id": user.id}})
            else:
                return Response({"code": 1, "msg": "密码错误"})
        except User.DoesNotExist:
            return Response({"code": 1, "msg": "用户不存在"})

class RegisterView(APIView):
    def post(self, request):
        serializer = UserInfoDto(data=request.data)
        if serializer.is_valid():
            phone = serializer.validated_data['phone']
            password = serializer.validated_data['password']

            if User.objects.filter(phone=phone).exists():
                return Response({"code": 1, "msg": "手机号已存在"})

            user = User.objects.create(
                phone=phone,
                password=make_password(password)
            )
            return Response({"code": 0, "msg": "", "data": {"user_id": user.id}})
        else:
            return Response({"code": 1, "msg": "参数错误"})